<template>
    <el-dialog :model-value="props.isConfirmDialogVisible" :show-close="false" modal-class="customize-dialog"
        :append-to-body="true" :close-on-click-modal="false" align-center width="85%">
        <template #header="{ titleId, titleClass }">
            <div class="flex justify-between items-center dialog-header">
                <div class="flex items-center">
                    <h4 :id="titleId" :class="titleClass">已生成</h4>
                    <span class="flex items-center">关键词组合 <el-text type="primary"
                            class="!text-20px font-bold !pl-6px !pr-6px">{{ total }}</el-text> 个</span>
                </div>
                <div class="flex items-center">
                    <el-button type="primary" size="small" class="mr-10px" @click="handleExport">导出问题表</el-button>
                    <svg-icon size="16px" icon-class="close-line" @click="closeDialog"></svg-icon>
                </div>
            </div>
        </template>
        <div>
            <div class="h-400px overflow-hidden">
                <el-scrollbar :always="true">
                    <template v-if="frontWordsBack.length">
                        <div class="flex items-center word-title">前置 + 主关键词 + 后置 <svg-icon size="16px"
                                icon-class="arrow-down-s-fill"></svg-icon></div>
                        <ul class="flex flex-wrap">
                            <li v-for="(item, index) in frontWordsBack" :key="index"
                                :class="{ 'active': handleActive(item) }">{{
                                    item }}<svg-icon size="16px" icon-class="close-line"
                                    @click="handleDelWord(item)"></svg-icon>
                            </li>
                        </ul>
                    </template>
                    <template v-if="cusKeyword.length">
                        <div class="flex items-center word-title">自定义关键词 <svg-icon size="16px"
                                icon-class="arrow-down-s-fill"></svg-icon></div>
                        <ul class="flex flex-wrap">
                            <li v-for="(item, index) in cusKeyword" :key="index"
                                :class="{ 'active': handleActive(item) }">
                                {{ item }}</li>
                        </ul>
                    </template>
                    <template v-if="freedomWords.length">
                        <div class="flex items-center word-title">自由问题关键词 <svg-icon size="16px"
                                icon-class="arrow-down-s-fill"></svg-icon></div>
                        <ul class="flex flex-wrap">
                            <li v-for="(item, index) in freedomWords" :key="index"
                                :class="{ 'active': handleActive(item) }">
                                {{ item }}</li>
                        </ul>
                    </template>
                </el-scrollbar>
            </div>
        </div>
        <div class="w-full mt-15px mb-10px remind">
            1、若组合语义不通畅，未自行处理，导致产生不通畅排名，我方不对此负责。<br>
            2、若组合语义不清，未自行处理，导致产生不清排名，我方不对此负责。
        </div>
        <div>
            <el-checkbox v-model="agree">同意服务协议</el-checkbox>
        </div>
        <div class="flex flex-center mt-16px mb-16px">
            <el-button @click="emit('closeDialog')">取消</el-button>
            <el-button @click="handleConfirm" type="primary">预确定</el-button>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { exportKeywordApi } from '@/api/geoBasic'
import { formatLabels,getFreedomWordID,checkGeo } from '@/utils/index'
import { useUserStore } from '@/store/modules/user'

const props = defineProps<{
    isConfirmDialogVisible: boolean,
    ruleForm: any
}>()

const emit = defineEmits(['closeDialog', 'confirm'])

const userStore = useUserStore()

const agree = ref(true)

const frontWordsBack = computed(() => {
    return props.ruleForm.FMBWords
})

const cusKeyword = computed(() => {
    if (props.ruleForm.cusKeyword.length) {
        return props.ruleForm.cusKeyword.split('/')
    } else {
        return []
    }
})

const freedomWords = computed(() => {
    if (props.ruleForm.freedomWords.length) {
        return props.ruleForm.FreedomWords
    } else {
        return []
    }
})

const total = computed(() => {
    const sum = frontWordsBack.value.length + cusKeyword.value.length + freedomWords.value.length
    if (!sum) {
        return 0
    } else if (sum < delWordLen.value) {
        return sum
    } else {
        return sum - delWordLen.value
    }
})

const delWordLen = computed(() => {
    if (!props.ruleForm.deleteWord.length) {
        return 0
    }
    if (props.ruleForm.deleteWord.indexOf('/') !== -1) {
        return props.ruleForm.deleteWord.split('/').length
    } else {
        return 1
    }
})

function closeDialog() {
    emit('closeDialog')
}

async function handleConfirm() {
    if (!agree.value) {
        ElMessage.error('请勾选同意服务协议')
    } else {
        emit('confirm')
        emit('closeDialog')
    }
}

function handleDelWord(word: string) {
    let d = props.ruleForm.deleteWord.split('/')
    //第一种情况（多个） props.ruleForm.deleteWord = **/**/**
    if (props.ruleForm.deleteWord.length > 0 && d.length > 1) {
        if (d.includes(word)) {
            // 从后向前遍历避免索引错位
            for (let i = d.length - 1; i >= 0; i--) {
                if (d[i] === word) {
                    d.splice(i, 1); // 删除当前元素
                }
            }
            props.ruleForm.deleteWord = d.join('/')
        } else {
            props.ruleForm.deleteWord += '/' + word
        }
    } else if (props.ruleForm.deleteWord.length > 0 && d.length == 1) {
        //第二种情况（一个） props.ruleForm.deleteWord = **
        if (props.ruleForm.deleteWord.includes(word)) {
            props.ruleForm.deleteWord = ''
        } else {
            props.ruleForm.deleteWord += '/' + word
        }
    } else {
        //第三种情况（没有） props.ruleForm.deleteWord = ''
        props.ruleForm.deleteWord += word
    }
}

function handleActive(str: string) {
    return props.ruleForm.deleteWord.split('/').includes(str)
}

async function handleExport() {
    const { api } = checkGeo(userStore.geo)
    const res = await exportKeywordApi(api,{
        zhukey: formatLabels(props.ruleForm.mainWords),
        leftkeydata: props.ruleForm.frontWords,
        rightkeydata: props.ruleForm.backWords,
        cuskey: props.ruleForm.cusKeyword,
        deletekey: props.ruleForm.deleteWord,
        Freedoms: getFreedomWordID(props.ruleForm.freedomWords),
        Type: props.ruleForm.combinationOptions
    })

    if (res.code === 200) {
        const downloadLink = document.createElement('a');
        downloadLink.href = res.data;
        downloadLink.download = `${res.dataname}.xlsx`;
        downloadLink.click();
        downloadLink.remove()
    }
}
</script>

<style lang="scss" scoped></style>